package intranet.client;
/**
 * @author BAKHTI Yassine
 *
 */



import intranet.client.Session;

import java.util.HashMap;


import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;


/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class ProfileTab extends VerticalPanel {
	String prevpass = null;
	String gransoft=null;
	
	private final static String EMAIL_VALIDATION_REGEX = "[a-z0-9!#$%&'*+/ =?^_`{|}~-]+(?:\\.[a-z0-9!#$% &'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
	private Session session;
	

	Grid grid1 = new Grid(5, 5);
	Grid grid2 = new Grid(3, 3);
	Grid grid3 = new Grid(1, 1);
	protected HashMap<String, String[]> teacherMap;
			
	
	protected VerticalPanel mainpanel = new VerticalPanel();
	
	protected ValidTextBox login_textbox = new ValidTextBox();
	protected ValidTextBox firstname_textbox = new ValidTextBox();
	protected ValidTextBox secondname_textbox = new ValidTextBox();	
	protected ValidTextBox officephone_textbox = new ValidTextBox();
	protected TextBox email1_textbox = new TextBox();
	
	protected PasswordTextBox previouspass_textbox = new PasswordTextBox();
	protected PasswordTextBox newpass_textbox = new PasswordTextBox();
	protected PasswordTextBox retypenewpass_textbox = new PasswordTextBox();
   
	//*****************************************************************************
	
	protected Label login_label = new Label("Login");
	protected Label firstname_label = new Label("Nom");
	protected Label secondname_label = new Label("Prenom");
	protected Label officephone_label = new Label("Tel.bur");		
	protected Label email1_label = new Label("Email1");
	
	protected Label previouspass_label = new Label("Ancien mot de passe");
	protected Label newpass_label = new Label("Nouveau mot de passe");
	protected Label retypenewpass_label = new Label("retaper le nouveau mot de passe");
	
	//******************************************************************************
	protected Button send = new Button();

//*******************************************	
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	
	private ProfileServiceAsync Profileservice = GWT
	.create(ProfileService.class);
	
	/**
	 * This is the entry point method.
	 */
	
	public  ProfileTab(Session sess) 
	{
		
		session=sess;
		mainpanel.setHorizontalAlignment(ALIGN_CENTER);
		mainpanel.setSize(Window.getClientWidth()*15/20+"px",Window.getClientHeight()*8/10+"px");
	
		
		grid1.setWidget(0, 0, login_label);		
		login_textbox.setEnabled(false);
		grid1.setWidget(0, 1, login_textbox);
		
		grid1.setWidget(1, 0, firstname_label);
		grid1.setWidget(1, 1, firstname_textbox);
		
		
		grid1.setWidget(2, 0, secondname_label);
		grid1.setWidget(2, 1, secondname_textbox);
		
		grid1.setWidget(3, 0, officephone_label);
		grid1.setWidget(3, 1, officephone_textbox);
		
		grid1.setWidget(4, 0, email1_label);
		grid1.setWidget(4, 1, email1_textbox);
		
		grid2.setCellSpacing(10);
		grid2.setWidget(0, 0, previouspass_label);
		grid2.setWidget(0, 1, previouspass_textbox);
		
		grid2.setWidget(1, 0, newpass_label);
		grid2.setWidget(1, 1, newpass_textbox);
		
		grid2.setWidget(2, 0, retypenewpass_label);
		grid2.setWidget(2, 1, retypenewpass_textbox);
		
		
		send.setText("Valider");
		send.addStyleDependentName( "send" );
		
		send.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event){
				
				if (firstname_textbox.getText().equals(""))
					firstname_textbox.addStyleName("error");
				else
					firstname_textbox.removeStyleName("error");
				
				if (secondname_textbox.getText().equals(""))
					secondname_textbox.addStyleName("error");
				else
					secondname_textbox.removeStyleName("error");
				
				if (officephone_textbox.getText().equals(""))
					officephone_textbox.addStyleName("error");
				else
					officephone_textbox.removeStyleName("error");
				
				if (email1_textbox.getText().equals(""))
					email1_textbox.addStyleName("error");
				else
					email1_textbox.removeStyleName("error");
				
				

				updatedata();}

		});
		
		grid3.setCellSpacing(30);
		grid3.setWidget(0, 0, send);
		
		mainpanel.add(new HTML ("Informations personnelles"));
		mainpanel.add(grid1);
		mainpanel.add(grid2);	
		mainpanel.add(grid3);
		
		getdata();		
		this.add(mainpanel);
		
		
	}
	
	/**
	 * sélectionner les données à partir d'une base de données
	 */
	protected void getdata() {
		
		
			String reqTeacher ="select teacher_login,teacher_name,teacher_firstname,teacher_email,teacher_tel from teacher where teacher_login="+"'"+session.get("teacher_login")+"'";
			Profileservice.select(reqTeacher, new  AsyncCallback<HashMap<String,String[]>>()
					{			
				@SuppressWarnings("unchecked")
				public void onSuccess( HashMap<String, String[]> result )
					{
					
					teacherMap=(HashMap<String, String[]>)result.clone();
				
					setdata();
						
					}
				
						public void onFailure( Throwable caught ) {
							
							Window.alert("erreur bado");
							}

					
					
					});		
	
		
		
	}
	
	/**
	 * valider l'adresse e-mail
	 * @param email
	 * @return boolean
	 */
	
	protected boolean validateEmailAddress(String email) { 
		 		                 boolean res=true;
		 		                 if (email.matches(EMAIL_VALIDATION_REGEX)) { 
		 		                	 res=true;
		 		                 } else{
		 		                	 
		 		                	 res=false;
		 		                 }
		 		                 
		 		                 return res;
		 		 } 
 
	/**
	 * mettre dans la zone de texte des données à partir d'une HashMap
	 */
	
	protected void setdata() {
		
		login_textbox.setText(teacherMap.get("teacher_login")[0]);
		firstname_textbox.setText( teacherMap.get("teacher_name")[0] );
		secondname_textbox.setText( teacherMap.get("teacher_firstname")[0]);	
		officephone_textbox.setText( teacherMap.get("teacher_tel")[0]);
		email1_textbox.setText( teacherMap.get("teacher_email")[0] );

		
	}
/**
 * mise à jour des données et la vérification des zones de texte
 */
	protected void updatedata() {
		 String email = email1_textbox.getText();
		 
		if(email1_textbox.getText().equals("")|| officephone_textbox.getText().equals("")|| login_textbox.getText().equals("")|| firstname_textbox.getText().equals("") || secondname_textbox.getText().equals("")){
						
			Window.alert("les champs sont vides ");
			
		}else
			
			
		if (!validateEmailAddress(email)){
				
				Window.alert("vérifiez le format de votre adresse e-mail ");
			}else
		
		if(previouspass_textbox.getText().equals("")){
			
		//**********************************************************************	
			String strreq1 = "update teacher SET teacher_name="+"'"+firstname_textbox.getText().toString()+"'"+","+
			"teacher_firstname="+"'"+secondname_textbox.getText().toString()+"'"+","+
			"teacher_tel="+"'"+officephone_textbox.getText().toString()+"'"+","+
			"teacher_email="+"'"+email1_textbox.getText().toString()+"'"+
			
			" where teacher.teacher_login="+"'"+login_textbox.getText().toString()+"'"+";";                           

			Profileservice.update(strreq1, new AsyncCallback<Integer>()
				                                {
				                                    public void onFailure(
				                                            Throwable caught)
				                                    {
				                                        Window.alert("Data insert : "+SERVER_ERROR);
				                                    }

				                                    public void onSuccess(Integer result)
				                                    {	                                  
				                                    	
				                                    	Window.alert("Mise à jour effectuée avec succès");
				                                    	
				                                    }
				                                });
			
	//***************************************************************************	
		}
		
		else{	
		
			 if(newpass_textbox.getText().compareTo(retypenewpass_textbox.getText())!=0){
				
				Window.alert("les nouveaux mots de passes ne sont pas identiques");
			}
				else if( newpass_textbox.getText()=="" || retypenewpass_textbox.getText()=="" || previouspass_textbox.getText()==""){	
					
					Window.alert("les champs sont vides ");
				}
			
				else if( newpass_textbox.getText().toString()!=""  && retypenewpass_textbox.getText().toString()!="" && previouspass_textbox.getText().toString()!="" && email1_textbox.getText().toString()!="" && officephone_textbox.getText().toString()!="" && login_textbox.getText().toString()!="" && firstname_textbox.getText().toString()!="" && secondname_textbox.getText().toString()!=""){
				

					
					Profileservice.updat(login_textbox.getText().toString(),
					firstname_textbox.getText().toString(),
					secondname_textbox.getText().toString(),
					officephone_textbox.getText().toString(),
					email1_textbox.getText().toString(),
					newpass_textbox.getText().toString(),
					new AsyncCallback<Integer>()
				                                {
				
			      public void onSuccess(Integer result)
			      
                  {
                  	
                  	if(result!=0)
                  	Window.alert("Mise à jour effectuée avec succès");
                  	
                  }
				   public void onFailure(Throwable caught)
				                                    {
				                                        Window.alert("erreur database : "+SERVER_ERROR);
				                                    }

				                              
				                                });
	
			}//end if send
		}	
			
		}
	
	
}
